
package com.example.testandroid;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

public class TargetPonitAddView extends FrameLayout {

    private static final int LONG_PRESS_TIME = (int) (1 * 1000); // 1.5S
    private long mKeyDownTime = -1;
    private OnPointAddedListener mPointAddedListener;

    public interface OnPointAddedListener {
        public void onNewPointAdded();
    }

    public TargetPonitAddView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public TargetPonitAddView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public TargetPonitAddView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TargetPonitAddView(Context context) {
        super(context);
        init();
    }

    public void setPointAddedListener(OnPointAddedListener listener) {
        this.mPointAddedListener = listener;
    }

    private void init() {
        setClickable(true);
    }

    public int[] getCenter() {
        int[] centerPoint = new int[2];
        centerPoint[0] = getLeft() + getMeasuredWidth() / 2;
        centerPoint[1] = getTop() + getMeasuredHeight() / 2;
        return centerPoint;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        System.out.println("yadong ---" + action);
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mKeyDownTime = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                // Long click to add point
                if (System.currentTimeMillis() - mKeyDownTime > LONG_PRESS_TIME) {
                    View point = LayoutInflater.from(getContext())
                            .inflate(R.layout.target_point_view, this, false);
                    LayoutParams layoutParams = (LayoutParams) point.getLayoutParams();
                    layoutParams.setMargins((int) (event.getX() - point.getMeasuredWidth() / 2),
                            (int) (event.getY() - point.getMeasuredHeight() / 2), 0, 0);
                    addView(point, layoutParams);
                    if (mPointAddedListener != null) {
                        mPointAddedListener.onNewPointAdded();
                    }
                }
                break;
            default:
                break;
        }
        return true;
    }

}
